﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Rose.Models;


namespace Rose.Helper
{
    public class FriendRelationHelpModel
    {
        private  Database_RoseEntities db = new Database_RoseEntities();

        #region  RequestToFriend
        private  bool RequestToFriend(RequestFriend model)
        { 
            try
            {
                db.AddToRequestFriends(model);
                db.SaveChanges();
                return true;
            }
            catch 
            {
                return false;
            }
        }
        public  bool RequestToFriend(string selfId, string friendId)
        {
            try
            {
                if (!IsRelationExist(selfId, friendId)&&!IsRequestExist(selfId,friendId))
                {
                    RequestFriend requestFriend = new RequestFriend()
                    {
                        Id = Guid.NewGuid(),
                        UserId = selfId,
                        TargetId = friendId,
                        CreateTime = DateTime.Now,
                        IsAccepted = false,
                        IsResponsed = false

                    };
                    RequestToFriend(requestFriend);
                }
                
                return true;
            }
            catch 
            {
                return false;
            }
        }

       


        #endregion

        #region  AcceptRequestNotUpdateCount  AcceptRequestAndUpdateCount
        /// <summary>
        /// 接受了好友请求，但是没有更新数据库的好友数量，需要调用Update UpdateFriendCount();
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private  bool AcceptRequestNotUpdateCount(string  requestId)
        {
            
            Guid guidId = new Guid(requestId);
            RequestFriend request  = db.RequestFriends.Where(c => c.Id == guidId).First();
           
            try
            {
                request.IsAccepted = true;
                request.IsResponsed = true;
                
                db.SaveChanges();
                
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 必须保证selfId 已经 friendId 是存在的
        /// </summary>
        /// <param name="reqeust">检查是否存在</param>
        /// <param name="selfId">检查是否存在</param>
        /// <param name="friendId"></param>
        /// <returns></returns>
        private  bool AcceptRequestAndUpdateCount(string  reqeustId,string selfId,string friendId)

        {
            if (AcceptRequestNotUpdateCount(reqeustId))
            {
                //UpdateFriendCount(selfId, true);
                //UpdateFriendCount(friendId, true);
                return true;
            }
            return false;
        }

        public  bool AcceptRequestAndCreateRelation(string  requestId, string selfId, string friendId)
        {
            if (AcceptRequestAndUpdateCount(requestId, selfId, friendId))
            {
                if (CreateFriendRelation(selfId, friendId))
                    return true;
                return false;
            }
            return false;
        }
        
        #endregion

        #region  RejectRequest
        public  bool RejectRequest(string requestId)
        {
            try
            {
                
                Guid guidId=new Guid(requestId);
                RequestFriend request = db.RequestFriends.Where(c => c.Id == guidId).FirstOrDefault();
                if (request == null)
                    return false;
                request.IsAccepted = false;
                request.IsResponsed = true;
                db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

      

        #endregion

        #region  UpdateFriendCount


        private   int UpdateFriendCount(string userId, bool isAdd)
        {
             
            UserInfo userInfo = db.UserInfos.Where(c => c.Id == userId).First();
            if (isAdd)
            {
                userInfo.FriendCount += 1;
                userInfo.Score += int.Parse(Rose.ViewRes.Defaultresx.FriendAddScore);
            }
            else
            {
                userInfo.FriendCount -= 1;
                userInfo.Score -= int.Parse(Rose.ViewRes.Defaultresx.FriendAddScore);
            }
            if (userInfo.FriendCount < 0)
                userInfo.FriendCount = 0;
            db.SaveChanges();
            return userInfo.FriendCount;
            //这里返回的数值是多少我也是不清楚的，研究一下

            
        }

        #endregion

        #region FeedBack
        private   List<RequestFriend> GetAcceptFeedBacks(string selfId)
        {
            //UserInfo userInfo = CheckHelpModel.CheckUserInfo(selfId);
            return (from request in db.RequestFriends
                   where request.UserId == selfId && request.IsResponsed == true && request.IsAccepted == true 
                   select request ).ToList();
                                                  
            
        }
        private   List<RequestFriend> GetRejectFeedBacks(string selfId)
        {
            //UserInfo userInfo = CheckHelpModel.CheckUserInfo(selfId);
            return (from request in db.RequestFriends
                    where request.UserId == selfId  && request.IsResponsed == true && request.IsAccepted == false
                    select request).ToList();
        }

        private  List<RequestFriend> GetUnSettledFeedBacks(string selfId)
        {
            //UserInfo userInfo = CheckHelpModel.CheckUserInfo(selfId);
            return (from request in db.RequestFriends
                    where request.UserId == selfId && request.IsResponsed==false
                    select request).ToList();
        }

        private  List<RequestModel> ChangeSelfRequestFriendToRequestModel(List<RequestFriend> requestList)
        {
            List<RequestModel> returnModel = new List<RequestModel>();
            foreach (var request in requestList)
            {
                try
                {
                    UserInfo friendInfo =new  CheckHelpModel().CheckUserInfo(request.TargetId);
                    RequestModel addModel = new RequestModel()
                    {
                        RequestId = request.Id.ToString(),
                        RequestName = friendInfo.Name,
                        Gender = friendInfo.Gender,
                        Address = friendInfo.Address,
                        ImagePath = friendInfo.ImagePath,
                        SchoolYear = friendInfo.SchoolYear.ToString(),
                        UserId = friendInfo.Id,
                        MajorClass = friendInfo.CollegeMajorClass,
                       University=friendInfo.University,
                        Hobbies = new UserInfoHelpModel().GetHobbies(friendInfo.Id)
                    };
                    returnModel.Add(addModel);
                }
                catch
                {
                    continue;
                }
            }
            return returnModel;
        }

        public  List<RequestModel> GetAcceptRequestFeedBacks(string selfId)
        {
            //UserInfo userInfo = CheckHelpModel.CheckUserInfo(selfId);
            List<RequestFriend> requestList = GetAcceptFeedBacks(selfId);

            return ChangeSelfRequestFriendToRequestModel(requestList);
        }

        public  List<RequestModel> GetRejectRequestFeedBacks(string selfId)
        {
            //UserInfo userInfo = CheckHelpModel.CheckUserInfo(selfId);
            List<RequestFriend> requestList = GetRejectFeedBacks(selfId);
            return ChangeSelfRequestFriendToRequestModel(requestList);
        
        }

        public  List<RequestModel> GetUnSettledRequestFeedBacks(string selfId)
        {
            //UserInfo userInfo = CheckHelpModel.CheckUserInfo(selfId);
            List<RequestFriend> requestList = GetUnSettledFeedBacks(selfId);
            return ChangeSelfRequestFriendToRequestModel(requestList);
        }

        public  int GetAcceptFeedBackCount(string selfId)
        {
            return GetAcceptFeedBacks(selfId) == null ? 0 : GetAcceptFeedBacks(selfId).Count();
        }

        public  int GetRejectFeedBackCount(string selfId)
        {
            return GetRejectFeedBacks(selfId) == null ? 0 : GetRejectFeedBacks(selfId).Count();
        }

        public  int GetUnSettledFeedBackCount(string selfId)
        {
            return GetUnSettledFeedBacks(selfId) == null ? 0 : GetUnSettledFeedBacks(selfId).Count();
        }

        #endregion

        #region GetRequests  GetRequestFromOthers
        private   List<RequestFriend> GetRequests(string selfId)
        {
            //UserInfo userInfo = CheckHelpModel.CheckUserInfo(selfId);
            return (from request in db.RequestFriends
                    where request.TargetId == selfId && request.IsResponsed == false
                    select request
                        ).ToList();

        }

        public  List<RequestModel> GetRequestFromOthers(string selfId)
        {
            //UserInfo selfInfo = CheckHelpModel.CheckUserInfo(selfId);
            List<RequestModel> returnModel = new List<RequestModel>();
            List<RequestFriend> requestList = GetRequests(selfId);
            foreach (var request in requestList)
            {
                try
                {
                    UserInfo requestInfo =new CheckHelpModel().CheckUserInfo(request.UserId);
                    RequestModel addModel = new RequestModel()
                    {
                        RequestId = request.Id.ToString(),
                        RequestName = requestInfo.Name,
                        Gender = requestInfo.Gender,
                        Address = requestInfo.Address,
                        ImagePath = requestInfo.ImagePath,
                        SchoolYear = requestInfo.SchoolYear.ToString(),
                        UserId = requestInfo.Id,
                        MajorClass = requestInfo.CollegeMajorClass,
                       University=requestInfo.University,
                        Hobbies = new UserInfoHelpModel().GetHobbies(requestInfo.Id)
                    };
                    returnModel.Add(addModel);
                }
                catch
                {
                    continue;
                }

            }
            return returnModel;
        }

        #endregion

        #region CreateFriendRelation
        private  bool CreateFriendRelation(string selfId,string friendId)
        {
            DateTime currentTime = DateTime.Now;
            try
            {
                AddFriendToRelation(selfId, friendId, currentTime);
                //第一份好友关系数据库保存
                AddFriendToRelation(friendId, selfId, currentTime);
                
              
                //another datetable is add to friend's friendRelation table
                return true;

            }
            catch 
            {
                return false;
            }
        }

        private  void AddFriendToRelation(string selfId, string friendId,DateTime currentTime)
        {
            //关系不存在
            if (!IsRelationExist(selfId, friendId))
            {
                FriendRelation selfRelation = new FriendRelation()
                {
                    Id = Guid.NewGuid(),
                    UserId = selfId,
                    CreateTime = currentTime,
                    FriendId = friendId,
                    IsShield = false
                };
                db.AddToFriendRelations(selfRelation);
                db.SaveChanges();
                UpdateFriendCount(selfId, true);
                //同时增加好友数量
            }
        }
       
        #endregion

        #region DeleteSingleFriendRelation  RemoveFriendFromRelation

        public  bool DeleteSingleFriendRelation(string selfId, string friendId)
        {
            if (RemoveFriendFromRelation(selfId, friendId))
            {
                
                return true;
            }
            return false;
        }

        
        
        //private  bool RemoveFriendFromRelation(FriendRelation model)
        //{
        //    try
        //    {
               
        //        db.FriendRelations.DeleteObject(model);
        //        db.SaveChanges();
        //        return true;

        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}
        private  bool RemoveFriendFromRelation(string selfId, string friendId)
        {
            try
            {
                if (IsRelationExist(selfId, friendId))
                {
                    
                    FriendRelation model = db.FriendRelations.Where(c => c.UserId == selfId && c.FriendId == friendId).First();
                    db.FriendRelations.DeleteObject(model);
                    db.SaveChanges();
                    
                    UpdateFriendCount(selfId, false);
                }
                return true;
            }
            catch
            {
                return false;

            }
        }

        #endregion

        #region DeleteRequestRelation

        public  bool DeleteRequestRelation(string requestFriendId)
        {

            try
            {

                
                Guid guidId = new Guid(requestFriendId);
                RequestFriend model = db.RequestFriends.Where(c => c.Id == guidId).FirstOrDefault();
                if (model == null)
                    return true;
                //because the requestFriend is not exist;
                db.RequestFriends.DeleteObject(model);
                db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }

        }

        #endregion


        #region helpcheck

        public bool IsRequestExist(string selfId,string friendId)
        {

            var returnModel = db.RequestFriends.Where(c => c.UserId == selfId && c.TargetId == friendId);

            return returnModel.Count() > 0 ? true : false;
        }

        public  bool IsRequestExist(string requestId)
        {

            var returnModel = db.RequestFriends.Where(c => c.Id == new Guid(requestId));

            return returnModel.Count() > 0 ? true : false;
        }

        public   bool IsRelationExist(string selfId, string friendId)
        {
            var returnModel = db.FriendRelations.Where(c => c.UserId == selfId && c.FriendId == friendId);
            return returnModel.Count() > 0 ? true : false;
        }
        

        #endregion

        #region GetFriendUserInfoList  GetFriendAbstractList

        private  List<UserInfo> GetFriendUserInfoList(string selfId)
        {
            //UserInfo selfInfo = CheckHelpModel.CheckUserInfo(selfId);
            List<UserInfo> returnModel = new List<UserInfo>();
            //check if selfInfo is null;
            List<FriendRelation> relations = db.FriendRelations.Where(c => c.UserId == selfId).ToList();
            foreach (var relation in relations)
            {

                try
                {
                    UserInfo userInfo =new  CheckHelpModel().CheckUserInfo(relation.FriendId);
                    returnModel.Add(userInfo);
                }

                catch
                {
                    continue;
                }
                
            }
            return returnModel;
        }

        public  List<RecommendModel> GetFriendAbstractList(string selfId,int currentpage,int pagesize)
        {
            List<RecommendModel> returnModel = new List<RecommendModel>();
            var recommendList = GetFriendUserInfoList(selfId);
            //if (recommendList.Count() <= 0)
            //    return null;

            foreach (UserInfo recommend in recommendList)
            {
                RecommendModel addModel = new RecommendModel()
                {
                    UserId = recommend.Id,
                    TrueName = recommend.Name ?? string.Empty,
                    ImagePath = recommend.ImagePath ?? string.Empty,
                    Address = recommend.Address ?? string.Empty,
                    University=recommend.University??string.Empty,
                    MajorClass = recommend.CollegeMajorClass ?? string.Empty,
                    SchoolYear = recommend.SchoolYear.ToString(),
                    Hobbies = new UserInfoHelpModel().GetHobbies(recommend.Id) ?? string.Empty,
                    Gender = recommend.Gender,
                    College=recommend.College
                };
                returnModel.Add(addModel);
            }
            return returnModel;
        }

        public  int GetFriendsCount(string selfId)
        {
            return GetFriendUserInfoList(selfId) == null ? 0 : GetFriendUserInfoList(selfId).Count();
        }

        #endregion

        ///////为完善的部分，需要定期删除没有回应的邀请码
        
        public  void DeleteOutTimeRequestFriend(TimeSpan timeSpan)
        { 
            
            ////

        }

        private  void AddInviteFriendScore(string selfId)
        { 
            ///
        }

        public  RequestModel GetRequestFriend(string requestId)
        {
            RequestFriend requestFriend =new CheckHelpModel().CheckRequestFriend(requestId);
            UserInfo requestInfo =new CheckHelpModel().CheckUserInfo(requestFriend.UserId);
            RequestModel returnModel = new RequestModel()
            {


                RequestId = requestId,
                RequestName = requestInfo.Name,
                Gender = requestInfo.Gender,
                Address = requestInfo.Address,
                ImagePath = requestInfo.ImagePath,
                SchoolYear = requestInfo.SchoolYear.ToString(),
                UserId = requestInfo.Id,
                MajorClass = requestInfo.CollegeMajorClass,
                University = requestInfo.University,
                Hobbies = new UserInfoHelpModel().GetHobbies(requestInfo.Id)

            };
            return returnModel;
        }

        public  string InviteFriend(string selfId)
        {
            try
            {

                RequestFriend requestFriend = new RequestFriend()
                {
                    CreateTime = DateTime.Now,
                    Id = Guid.NewGuid(),
                    UserId = selfId,
                    TargetId = string.Empty,
                    IsAccepted = false,
                    IsResponsed = false

                };
                db.AddToRequestFriends(requestFriend);
                db.SaveChanges();
                return requestFriend.Id.ToString();
            }
            catch
            { return string.Empty; }
        }

        public  bool InviteFriendSuccess(string selfId,string friendId,string requestId)
        {
            if (AcceptRequestAndCreateRelation(requestId, selfId, friendId))
            {
                DeleteRequestRelation(requestId);
                return true;
            }
            return false;
        }


    }
}